import json
import logging
import os

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import channel

from models import Message, User


DURATION_IN_MINUTES = 60


class MainPage(webapp.RequestHandler):
  
    def get(self):
        template_values = {}
        if User.all().count(limit=2) == 2:
            template_filename = 'full.html'
        else:
            template_filename = 'index.html'
          
        path = os.path.join(os.path.dirname(__file__), template_filename)
        self.response.out.write(template.render(path, template_values))

    
class CreateChannelPage(webapp.RequestHandler):
    """
    When a user POSTs to this page, a channel is created   
    """
    def post(self):
        # Channel is created
        client_id = self.request.get('from')
        channel_token = channel.create_channel(client_id, DURATION_IN_MINUTES)
        
        # User is saved
        user = User.get_or_insert(key_name=client_id, client_id=client_id)
        is_caller = user.is_caller()
    
        # Returns json response
        json_response = json.dumps({
            'channelToken' : channel_token,
            'isCaller' :     is_caller,
        })
        self.response.headers.add_header('content-type', 'application/json', charset='utf-8')
        self.response.out.write(json_response)
        

class MessagePage(webapp.RequestHandler):
  
    def post(self):
        client_id = self.request.get('from')
        user = User.get_by_key_name(client_id)
        data = self.request.body
    
        # Save message for future incomer
        Message(client_id=client_id, data=data).put() 
        logging.info('Saved message from ' + client_id)
        
        # Broadcast message to all other users
        for other_user in user.get_other_users():
            channel.send_message(other_user.client_id, data)
            logging.info('Sent new message from ' + client_id + ' to ' + other_user.client_id + ' : ' + data )
    
    
class ConnectPage(webapp.RequestHandler):
  
    def post(self):
        client_id = self.request.get('from')
        user = User.get_by_key_name(client_id)
    
        logging.info('Connected user: ' + user.client_id)
    
        messages = Message.all().filter('client_id !=', client_id)
        for message in messages:
            channel.send_message(client_id, message.data)
            logging.info('Sent saved message from ' + message.client_id + ' to ' + client_id);


class DisconnectPage(webapp.RequestHandler):
  
    def post(self):
        client_id = self.request.get('from')
        user = User.get_by_key_name(client_id)
        user.delete();
        logging.info('Disconnected user: ' + user.client_id)
    
        messages = Message.all().filter('client_id =', client_id)
        for message in messages:
          message.delete()
        logging.info('Deleted messages for user: ' + user.client_id)
    
        # Broadcast bye to all other users
        for other_user in user.get_other_users():
            channel.send_message(other_user.client_id, '{ "type": "bye" }')
            logging.info('Sent bye message to ' + other_user.client_id)
    
    
application = webapp.WSGIApplication([
                                      ('/', MainPage),
                                      ('/createChannel/', CreateChannelPage),
                                      ('/message/', MessagePage),
                                      ('/_ah/channel/connected/', ConnectPage),
                                      ('/_ah/channel/disconnected/', DisconnectPage),
                                     ]
                                     ,debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
